package com.yc154.web;

import com.yc.damai.entity.Product;
import com.yc154.dao.ProductDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;

@RestController
@RequestMapping("product")
@Slf4j
public class ProductDo {

    @Autowired
    ProductDao productDao;

    @RequestMapping("queryAll")
    public Flux<Product> queryAll(){
        return productDao.findAll();
    }

    @RequestMapping("queryByName")
    public Flux<Product> queryByName( String pname){
        log.info("pname:{}",pname);
        return productDao.findByPnameContaining(pname);
    }

    // 组合条件的分页查询
    @RequestMapping("find")
    public Mono<?> findPage(Product product,
                                  @RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "5") int size){
        ExampleMatcher matcher = ExampleMatcher.matching()
                // 忽略大小写
                .withIgnoreCase()
                // 忽略空值
                .withIgnoreNullValues()
                // 设置pname字段模糊匹配 like
                .withMatcher("pname", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("pdesc", ExampleMatcher.GenericPropertyMatchers.contains());
        // 自动生成查询条件
        Example<Product> example = Example.of(product, matcher);
        int begin = (page - 1) * size;
        return productDao.findAll(example)
                // 跳过 begin 个元素
                .skip(begin)
                // 提取 size 个元素
                .take(size)
                // 收集结果到 list 中
                .collectList()
                // 查询数量, 返回 Map 集合
                .flatMap(products->{
                    // 查询总数, 封装到Map中返回
                    return productDao.count(example)
                            .map(total->{
                                return Map.of("total", total,
                                        "records", products);
                            });
                });

    }

}
